package org.hw.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class ImgUploadUtil {
    //第一个图片保存的位置
    //浏览器访问图片的路径
    private static final String BASE_PATH = "D:\\imgUpload\\";
    private static final String SERVER_PATH = "http://localhost:8080/upload/";

    //处理上传图片的方法
    public static String upload(MultipartFile multipartFile){
        if(multipartFile.isEmpty()){
            return "文件不存在";
        }
        //获取图片原始名称
        String filename = multipartFile.getOriginalFilename();
        //通过uuid生成唯一主键
        String id = UUID.randomUUID().toString().replace("-","");
        //生成唯一图片
        String newFileName = id+"-"+filename;
        //创建一个field实例
        File file = new File(BASE_PATH,newFileName);
        //将上传的图片保存到file中
        try {
            multipartFile.transferTo(file);
        }catch (IOException e){
            e.printStackTrace();
        }

        System.out.println(SERVER_PATH);
        return SERVER_PATH+newFileName;
    }
}
